package learn.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DuplexChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class Server {

    public static void main(String[] args) throws InterruptedException {

        //用于处理客户端连接请求，将请求发送给childGroup中的eventLoop
        NioEventLoopGroup parentGroup = new NioEventLoopGroup();
        //用于处理客户端请求
        NioEventLoopGroup childGroup = new NioEventLoopGroup();


        try{
            //用户启动ServerChannel
            ServerBootstrap bootstrap = new ServerBootstrap();
            //指定eventLoopGroup
            bootstrap.group(parentGroup,childGroup)
                    //指定用NIO进行通讯
                    .channel(NioServerSocketChannel.class)
                    //指定childGroup中的eventLoop所绑定的线程说要处理的处理器
                    .childHandler(new ChannelInitializer<DuplexChannel>());

            //指定当前服务器所监听的端口号
            //bind()方法的执行是异步的
            //sync()方法使bind()操作与后续的代码的执行由异步变成同步
            ChannelFuture future = bootstrap.bind(8888).sync();
            System.out.println("服务器启动成功。");
            //关闭Channel
            //closeFuture()的执行是异步的
            //当Channel调用了close()方法并关闭成功后才会触发closeFuture()方法的执行
            future.channel().closeFuture().sync();

        }finally {
            //优雅关闭   执行完再关闭
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}
